<template>
  <div class="p-2">
    <div class="search" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="区域查询" prop="regionId">
          <el-cascader
            :options="organizationTree.regionTree"
            v-model="queryParams.regionId"
            clearable
            :props="regionManageCascaderProps"
            :show-all-levels="false"
            @change="handleSearchRegionChange"
          >
            <template #default="{ node }">
              <span>{{ node.label }}</span>
            </template>
          </el-cascader>
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" clearable placeholder="请选择">
            <el-option
              v-for="item in selectArr.rootOrganizationTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <!-- 按钮区 -->
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAddRootOrganization()"
              v-hasPermi="['system:organization:add']"
            >
              新增根节点
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Sort"
              @click="handleToggleExpandAll"
            >
              展开/折叠
            </el-button>
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getOrganizationTree"
          ></right-toolbar>
        </el-row>
      </template>
      <el-table
        v-loading="loading"
        :data="organizationTree.organizationTree"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        ref="treeTableRef"
      >
        <el-table-column label="机构名称" align="left" prop="label" />

        <el-table-column label="状态" prop="status" width="80">
          <template #default="{ row }">
            <el-tag :type="CommonStatusStyleTypeMap.get(row.status)"
              >{{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="类型" align="center" prop="typeMsg" />

        <el-table-column
          label="所属区域"
          align="center"
          prop="regionMergerName"
          width="180"
        />

        <el-table-column label="创建时间" align="center" prop="createTime" />

        <!--        <el-table-column-->
        <!--          label="排序"-->
        <!--          align="center"-->
        <!--          width="60"-->
        <!--          prop="orderNum"-->
        <!--        />-->

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <span v-hasPermi="['system:organization:edit']">
              <el-tooltip content="修改" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleEdit(scope.row)"
                />
              </el-tooltip>
            </span>

            <span v-hasPermi="['system:organization:add']" class="ml-10px">
              <el-tooltip content="新增" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Plus"
                  @click="handleAddSubOrganization(scope.row)"
                />
              </el-tooltip>
            </span>

            <span v-hasPermi="['system:organization:remove']" class="ml-10px">
              <el-tooltip content="删除" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                />
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getOrganizationTree"
      />
    </el-card>

    <!-- 点击table列表dialog -->
    <el-dialog
      :title="dialogStatus.title"
      v-model="dialogStatus.isShow"
      width="450px"
      append-to-body
      center
      draggable
      @close="handleCloseDialog"
    >
      <el-form
        ref="addRootFormRef"
        :model="currentDialogData"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item
          label="所属机构"
          prop="parentName"
          v-show="dialogStatus.isNode"
        >
          <el-tooltip :content="fullName" :enterable="false" placement="top">
            <el-input
              disabled
              v-model="fullName"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-tooltip>
        </el-form-item>

        <el-form-item label="机构名称" prop="name">
          <el-input
            v-model="currentDialogData.name"
            placeholder="请输入区域名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="机构全程" prop="name">
          <el-input
            v-model="currentDialogData.fullName"
            placeholder="请输入区域名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item> -->

        <el-form-item label="所在区域" prop="regionId">
          <el-cascader
            ref="regionCascaderRef"
            :disabled="dialogStatus.isNode"
            v-model="currentDialogData.regionId"
            :options="organizationTree.regionTree"
            clearable
            collapse-tags
            :props="regionProps"
          >
            <template #default="{ node }">
              <span>{{ node.label }}</span>
            </template>
          </el-cascader>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select
            v-model="currentDialogData.status"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in selectArr.statusArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select
            v-model="currentDialogData.type"
            clearable
            placeholder="请选择"
            v-if="dialogStatus.isRoot"
          >
            <el-option
              v-for="item in selectArr.rootOrganizationTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-select
            v-model="currentDialogData.type"
            clearable
            placeholder="请选择"
            v-else
          >
            <el-option
              v-for="item in selectArr.subOrganizationTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" icon="Check" @click="addSubmit">
            确定
          </el-button>
          <el-button icon="Close" @click="handleCloseDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getOrganizationTree as getOrganizationTreeApi,
  createRootOrganization as createRootOrganizationApi,
  createOrganization as createOrganizationApi,
  getRegionTree as getRegionTreeApi,
  updateOrganization as organizationEditApi,
  getOrganizationDetail as getOrganizationDetailApi,
  deleteOrganization as deleteOrganizationApi,
  getAllOrganizationTypeList as getAllOrganizationTypeListApi,
  getRootOrganizationTypeList as getRootOrganizationTypeListApi,
  getSubOrganizationTypeList as getSubOrganizationTypeListApi,
} from "@/service/api/system/organization";
import { CascaderInstance, ElForm, ElTable, FormInstance } from "element-plus";
import to from "await-to-js";
import RightToolbar from "@/components/RightToolbar/index.vue";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import Pagination from "@/components/Pagination/index.vue";
import {
  OrganizationNode,
  RegionNode,
  SysDictDataVo,
  SysOrganizationVo,
} from "@/service/api/system/organization/types.ts";
import {
  CommonStatusMap,
  CommonStatusStyleTypeMap,
} from "@/maps/commonMaps.ts";
// import { OrganizationTypeMap } from "@/maps/system/organization/organizationMap.ts";
import { DialogModeEnum } from "@/enums/dialogEnum.ts";
import { removeButtonFocus } from "@/utils/focus.tsx";

const queryFormRef = ref(ElForm);

// 根节点dialogForm
const addRootFormRef = ref<FormInstance>();
const regionCascaderRef = ref<CascaderInstance>();

const tableIds = ref<string[]>([]);
const isExpandAll = ref(true);
const treeTableRef = ref(ElTable);
const showSearch = ref(true);
const loading = ref(false);

// const isRoot = ref(true);
const regionProps = {
  // checkStrictly: true,
  value: "id",
  emitPath: false,
};
const initQueryParams = {
  name: "",
  type: "",
  regionId: "",
  orderByColumn: "createTime",
  orderType: "desc",
  pageSize: 10,
  pageNum: 1,
}

const queryParams = reactive({
  name: "",
  type: "",
  regionId: "",
  orderByColumn: "createTime",
  orderType: "desc",
  pageSize: 10,
  pageNum: 1,
});

// 初始dialog数据
const initDialogData: SysOrganizationVo = {
  id: undefined,
  name: "",
  parentName: "",
  status: "",
  type: "",
  regionId: "",
  parentId: undefined,
};

const fullName = ref();

// 初始dialog状态
const initDialogStatus = {
  isShow: false,
  isRoot: false,
  isNode: false,
  mode: DialogModeEnum.NEW,
  title: "",
  isDisabled: false,
};
const dialogData = reactive({
  // 临时数据
  currentDialogData: {
    ...initDialogData,
  },
  // 控制dialog状态
  dialogStatus: { ...initDialogStatus },
  rules: {
    name: [{ required: true, message: "机构名不能为空", trigger: "blur" }],
    regionId: [
      { required: true, message: "机构地区不能为空", trigger: "change" },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    type: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});

const { currentDialogData, dialogStatus, rules } = toRefs(dialogData);
// 选择框数据
const selectArr = reactive({
  allOrganizationTypeList: <SysDictDataVo[]>[],
  rootOrganizationTypeList: <SysDictDataVo[]>[],
  subOrganizationTypeList: <SysDictDataVo[]>[],
  // 状态
  statusArr: [
    {
      value: "0",
      label: "正常",
    },
    {
      value: "1",
      label: "停用",
    },
  ],
});

const organizationTypeMap = new Map<string, string>();

// 树结构数据
const organizationTree = reactive({
  regionTree: <RegionNode[]>[],
  regionProps: {
    value: "id",
    checkStrictly: true,
    emitPath: false,
  },
  organizationTree: <OrganizationNode[]>[],
});
const regionManageCascaderProps = {
  checkStrictly: true,
  value: "id",
};
const total = ref(0);

/**
 * 获取组织树
 */
const getOrganizationTree = async (): Promise<boolean> => {
  loading.value = true;
  const [err, res] = await to<BasePageResponse<OrganizationNode>, any>(
    getOrganizationTreeApi(queryParams),
  );
  if (!err) {
    console.log(res);
    organizationTree.organizationTree = res?.rows ?? [];
    total.value = Number(res?.total);

    // 递归翻译状态码
    for (const tree of organizationTree.organizationTree) {
      updateNodeValue(tree, "");
    }
    loading.value = false;
    return true;
  }
  loading.value = false;
  return false;
};

/**
 * 获取地区id
 * @param selectedData
 */
 const handleSearchRegionChange = (selectedData: any) => {
  if (selectedData && selectedData.length > 0) {
    queryParams.regionId = selectedData[selectedData.length - 1];
  }
};

// /**
//  * 获取地区树
//  */
//  const getRegionTree = async () => {
//   const [err, res] = await to<BaseResponse<RegionNode[]>, any>(
//     getDefaultRegionTreeApi(),
//   );
//   if (!err) {
//     if (res && res.data) {
//       console.log(res);
//       searchData.searchRegionTree = res.data ?? [];
//     }
//   }
// };

// 提交查询按钮
const handleQuery = () => {
  getOrganizationTree();
};

// 重置按钮
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.regionId = ''
  console.log(queryParams);
  getOrganizationTree();
};

/**
 * 获取区域树
 */
const getRegionTree = async () => {
  const [err, res] = await to<BaseResponse<RegionNode[]>, any>(
    getRegionTreeApi(),
  );

  if (!err) {
    organizationTree.regionTree = res?.data ?? [];
  }
};

/**
 * 新增根组织节点
 */
const handleAddRootOrganization = async () => {
  dialogStatus.value.title = "新增根组织";
  dialogStatus.value.isRoot = true;
  // 没有parentId表示根
  // currentDialogData.value = { ...initDialogData };
  dialogStatus.value.mode = DialogModeEnum.NEW;
  dialogStatus.value.isShow = true;
  nextTick(() => {
    addRootFormRef.value?.clearValidate();
  });
};

const currentRegionId = ref();

/**
 * 处理编辑按钮
 * @param row
 */
const handleEdit = async (row: any) => {
  // 非根节点
  if (row.parentId !== "0") {
    // const currentTree = findTree(organizationTree.organizationTree, row);
    // console.log(currentTree);
    // // 拼接所有父节点名称
    // const nameArr = await getParentNames(row);
    // fullName.value = nameArr.reverse().join(" / ");

    const response = await getSubOrganizationTypeList(row.parent.type);

    if (response) {
      let index = row.fullName.lastIndexOf("/");
      fullName.value = row.fullName.substring(0, index);
      dialogStatus.value.title = "编辑组织";
      dialogStatus.value.isNode = true;
      dialogStatus.value.isRoot = false;
    }
  } else {
    dialogStatus.value.title = "编辑根组织";
    dialogStatus.value.isRoot = true;
    dialogStatus.value.isNode = false;
  }

  const [err, res] = await to<BaseResponse<SysOrganizationVo>, any>(
    getOrganizationDetailApi(row.id),
  );
  if (!err) {
    currentDialogData.value = res?.data ?? initDialogData;
    currentRegionId.value = res?.data?.regionId ?? "";
  }
  dialogStatus.value.mode = DialogModeEnum.EDIT;
  dialogStatus.value.isShow = true;
  nextTick(() => {
    addRootFormRef.value?.clearValidate();
  });
};

/**
 * 处理新增子节点
 * @param row
 */
const handleAddSubOrganization = async (row?: SysOrganizationVo) => {
  loading.value = true;
  console.log(row);
  fullName.value = row?.fullName;
  const [err, res] = await to<BaseResponse<SysOrganizationVo>, any>(
    getOrganizationDetailApi(row?.id ?? ""),
  );
  if (!err) {
    // 自身id作为父id
    // currentDialogData.value = {...initDialogData};
    // TODO:YX: 如果列表返回了regionId，此时就无需再查询
    currentDialogData.value.regionId = res?.data?.regionId ?? "";
    currentRegionId.value = row?.regionId;
    currentDialogData.value.parentId = row?.id;

    // 获取子组织类型
    const response = await getSubOrganizationTypeList(row?.type ?? "");

    if (response) {
      dialogStatus.value.title = "新增子组织";
      dialogStatus.value.isNode = true;
      dialogStatus.value.mode = DialogModeEnum.NEW;
      dialogStatus.value.isShow = true;
      nextTick(() => {
        addRootFormRef.value?.clearValidate();
      });
    }
  }
};

/**
 * 处理删除按钮
 * @param row
 */
const handleDelete = async (row?: any) => {
  loading.value = true;
  console.log(row);

  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm(`是否确定删除选中的机构——"${row.label}"？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消删除",
    });
  } else if (confirm === "confirm") {
    // todo: 多一层询问是否删除
    const [err] = await to(
      ElMessageBox.confirm(
        `该机构下有其他组织或者用户，是否要删除该节点？`,
        "警告",
        {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "warning",
        },
      ),
    );
    if (!err) {
      const ids = row.id || tableIds.value;
      const [err] = await to(deleteOrganizationApi(ids));
      if (!err) {
        getOrganizationTree();
        ElMessage({
          message: "删除成功",
          type: "success",
        });
      }
    } else {
      ElMessage({
        message: "取消成功",
        type: "success",
      });
    }
  }
  loading.value = false;
};

/**
 * 处理对话框的提交按钮
 */
const addSubmit = () => {
  addRootFormRef.value?.validate(async (valid: boolean) => {
    // 验证通过
    if (valid) {
      loading.value = true;
      // 修改
      if (dialogStatus.value.mode === DialogModeEnum.EDIT) {
        // 如果修改了地区
        if (currentRegionId.value != currentDialogData.value.regionId) {
          // 如果改变了根节点的地区
          // 找到根节点对应树
          // 保存新的regionId
          const newRegionId = currentDialogData.value.regionId;
          const currentTree = organizationTree.organizationTree.find(
            (item: any) => item.id === currentDialogData.value.id,
          );
          console.log(currentTree);
          // 遍历改变所有子节点的地区
          await updateNodeRegion(currentTree, newRegionId);
          loading.value = false;
        }
        // 未修改地区
        else {
          const [err] = await to(organizationEditApi(currentDialogData.value));
          if (!err) {
            dialogStatus.value = Object.assign({}, initDialogStatus);
            currentDialogData.value = Object.assign({}, initDialogData);
            // 等待删除完成？
            // setTimeout(async () => {
            //   await getOrganizationTree();
            // }, 1000);
            ElMessage({
              type: "success",
              message: "修改成功",
            });
          }
        }
      }
      // 无id为新增
      else {
        const [err] = dialogStatus.value.isRoot
          ? await to(createRootOrganizationApi(currentDialogData.value))
          : await to(createOrganizationApi(currentDialogData.value));
        if (!err) {
          dialogStatus.value = Object.assign({}, initDialogStatus);
          currentDialogData.value = Object.assign({}, initDialogData);
          // setTimeout(async () => {
          //   await getOrganizationTree();
          // }, 1000);
          ElMessage({
            type: "success",
            message: "新增成功",
          });
          loading.value = false;
        }
      }
      loading.value = false;
    }
  });
};

/**
 * 处理对话框关闭
 */
const handleCloseDialog = () => {
  // 初始化
  dialogStatus.value = Object.assign({}, initDialogStatus);
  currentDialogData.value = Object.assign({}, initDialogData);
  currentRegionId.value = "";
  addRootFormRef.value?.clearValidate();
  regionCascaderRef.value?.cascaderPanelRef?.clearCheckedNodes();
  getOrganizationTree();
};

// 展开折叠
const handleToggleExpandAll = (event: MouseEvent) => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(organizationTree.organizationTree, isExpandAll.value);
  removeButtonFocus(event);
};

/**
 * 展开/折叠操作
 */
const toggleExpandAll = (data: any, status: boolean) => {
  data.forEach((item: any) => {
    treeTableRef.value.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0)
      toggleExpandAll(item.children, status);
  });
};

/**
 * 遍历每个节点，将状态码变为文字描述
 * @param item
 * @param parentName
 */
const updateNodeValue = (item: OrganizationNode, parentName: string) => {
  item.statusMsg = CommonStatusMap.get(item.status) ?? "未知";
  item.typeMsg = organizationTypeMap.get(item.type) ?? "未知";

  let name: string;
  if (parentName !== "") {
    name = parentName + " / " + item.label;
  } else {
    name = item.label;
  }
  item.fullName = name;

  console.log(name);

  if (item.children) {
    for (const child of item.children) {
      child.parent = item;
      updateNodeValue(child, name); // 递归调用更新子节点
    }
  }
};

/**
 * 遍历每个节点更新region数据
 * @param item
 * @param newRegionId
 */
const updateNodeRegion = async (item: any, newRegionId: string) => {
  const [err, res2] = await to<BaseResponse<SysOrganizationVo>, any>(
    getOrganizationDetailApi(item.id),
  );

  if (!err) {
    console.log(res2?.data, res2?.data?.regionId);
    res2!.data!.regionId = newRegionId;
    console.log(res2?.data?.regionId, newRegionId);
    const res = await organizationEditApi(res2!.data);
    console.log(res);
    for (const child of item.children) {
      updateNodeRegion(child, newRegionId); // 递归调用更新子节点
    }
  }
};

/**
 * 获取所有组织类型
 */
const getAllOrganizationTypeList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<SysDictDataVo>, any>(
    getAllOrganizationTypeListApi(),
  );
  if (!err) {
    selectArr.allOrganizationTypeList = res?.rows ?? [];

    selectArr.allOrganizationTypeList.forEach((item) => {
      organizationTypeMap.set(item.value ?? "", item.label);
    });

    return true;
  }

  return false;
};

/**
 * 获取根组织类型
 */
const getRootOrganizationTypeList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<SysDictDataVo>, any>(
    getRootOrganizationTypeListApi(),
  );
  if (!err) {
    selectArr.rootOrganizationTypeList = res?.rows ?? [];

    return true;
  }

  return false;
};

/**
 * 获取子组织类型
 */
const getSubOrganizationTypeList = async (
  parentValue: string,
): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<SysDictDataVo>, any>(
    getSubOrganizationTypeListApi(parentValue),
  );
  if (!err) {
    selectArr.subOrganizationTypeList = res?.rows ?? [];

    return true;
  }

  return false;
};

// 关闭dialog时触发
// const closeDialog = () => {};

onMounted(async () => {
  getRegionTree();
  getRootOrganizationTypeList();
  await getAllOrganizationTypeList();
  getOrganizationTree();
  // getBackOrganizationTree();
});
</script>

<style scoped></style>
